const gulp = require('gulp')
const connect = require('gulp-connect')
const stylus = require('gulp-stylus')
const autoprefixer = require('gulp-autoprefixer')
const fileInclude = require('gulp-file-include')
const notify = require('gulp-notify')
const plumber = require('gulp-plumber')
const webpack = require('gulp-webpack')
const config = require('./config')

// 错误处理
const handlerError = function(err){
  // 错误通知
  notify.onError(err.toString().split(':').join(':\n')).apply(this,arguments)

  // 保持gulp挂载在此任务上
  if(typeof this.emit === 'function'){
    this.emit('end')
  }
}

// 编译es文件
gulp.task('es', function(){
  gulp.src('./src/js/*.js')
  .pipe(webpack(require('./webpack.config')))
  .pipe(gulp.dest('./dist/js'))
})

// 编译styl文件
gulp.task('stylus', function(){
  gulp.src('./src/stylus/*.styl')
  .pipe(plumber(handlerError))
  .pipe(stylus())
  .pipe(autoprefixer())
  .pipe(gulp.dest('./dist/css'))
})

// 引入html文件
gulp.task('include', function(){
  gulp.src('./src/page/*.html')
  .pipe(plumber(handlerError))
  .pipe(fileInclude({
    prefix: '@@',
    basepath: '@file',
  }))
  .pipe(gulp.dest('./dist'))
})

// 创建开发服务器
gulp.task('connect', function(){
  connect.server(config)
})

// reload HTML
gulp.task('reloadHTML', function(){
  gulp.src('./dist/*.html')
  .pipe(connect.reload())
})

// reload CSS
gulp.task('reloadCSS', function(){
  gulp.src('./dist/css/*.css')
  .pipe(connect.reload())
})

// reload JS
gulp.task('reloadJS', function(){
  gulp.src('./dist/js/*.js')
  .pipe(connect.reload())
})

// 监听文件
gulp.task('watch', function(){
  gulp.watch(['./src/js/**/*.js'], ['es'])
  gulp.watch(['./src/stylus/**/*.styl'], ['stylus'])
  gulp.watch(['./src/page/**/*.html'], ['include'])
  gulp.watch('./dist/*.html', ['reloadHTML'])
  gulp.watch('./dist/css/*.css', ['reloadCSS'])
  gulp.watch('./dist/js/*.js', ['reloadJS'])
})

// 对外命令
// gulp
gulp.task('default', ['stylus', 'include'])
// gulp dev
gulp.task('dev', ['stylus', 'include', 'connect', 'watch'])